package com.fourforfo.fourmall.product.exception;

import com.fourforfo.common.exception.BizCodeEnum;
import com.fourforfo.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;

/**
 * 集中处理所有异常
 *  1）统一管理字段检验类
 */
@Slf4j
/**
 * 注解RestControllerAdvice等同于@ResponseBody和@ControllerAdvice
 */
//@ResponseBody
//@ControllerAdvice(basePackages = "com.fourforfo.fourmall.product.controller")
@RestControllerAdvice(basePackages = "com.fourforfo.fourmall.product.controller")
public class fourmallControllerAdvice {

    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public R handleValidException(MethodArgumentNotValidException exception){
        log.error("数据校验出现问题{},异常类型: {}",exception.getMessage(),exception.getClass());
        BindingResult result = exception.getBindingResult();
        Map map = new HashMap();
        result.getFieldErrors().forEach((item)->{
            //封装错误信息
            map.put(item.getField(),item.getDefaultMessage());
        });
        return R.error(BizCodeEnum.VALID_EXCEPTION.getCode(), BizCodeEnum.VALID_EXCEPTION.getMsg()).put("data",map);
    }

    @ExceptionHandler(value = Throwable.class)
    public R handleException(Throwable throwable){
        log.error("错误:",throwable);
        return R.error(BizCodeEnum.UNKNOW_EXCEPTION.getCode(), BizCodeEnum.UNKNOW_EXCEPTION.getMsg());
    }
}
